package com.jacklei.ch13;

import com.sun.org.apache.bcel.internal.generic.LDC_W;

import java.awt.*;
import java.util.List;
import java.util.Queue;

/*
* 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。

 

示例 1：


输入：head = [1,2,3,4,5], n = 2
输出：[1,2,3,5]
示例 2：

输入：head = [1], n = 1
输出：[]
示例 3：

输入：head = [1,2], n = 1
输出：[1]
 

提示：

链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

来源：力扣（LeetCode）
链接：https://leetcode.cn/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。*/
public class RemoveNthNodeFromEndOfList {
    public static void main(String[] args) {
        RemoveNthNodeFromEndOfList r = new RemoveNthNodeFromEndOfList();
        ListNode listNode = new ListNode(
                1,new ListNode(
                        2/*,new ListNode(
                                3,new ListNode(
                                        4,new ListNode(5)
        )
        )*/
        )
        );
        r.removeNthFromEnd(listNode,1);
    }
    public static class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    //快慢指针 （其他思路 ： 遍历 、压栈）
    public ListNode removeNthFromEnd(ListNode head, int n) {
       if(head.next == null) return null;
       ListNode low = head;
       ListNode quick = head;
       int count = 1;
       while (quick.next != null && quick.next.next != null) {
           count +=2;

           low =low.next;
           quick= quick.next.next;
       }
       int curLow = (count >> 1) +1;
       count = quick.next == null ? count : count+1;
       if(curLow > (count - n)) {
           curLow =1;
           low =head;
       }
       while (curLow < (count - n)) {
           curLow++;
           low = low.next;
       }
        if(count - n ==0){
            low = head.next;
            head.next= null;
            return low;
        }else {
       quick = low.next;
       low.next = quick.next; //NullPointer
        quick.next = null;}

       return head;
    }
}
